var _ = require('lodash'),
    PublicEnum = require('../../../Base/server/controllers/Enum'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller');

// 交接区入库：写入库记录
exports.addStockQty = function (userID, barcodes, completeFun) {
    barcodeMasterController.findBarcodeMasters(barcodes, function (err, records) {
        if (err || !records) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '不能识别的条码，请检查查询参数！';
            completeFun(newErr);
            return;
        }
        var rcvRecords = [];
        _.forEach(records, function (record) {
            rcvRecords.push({
                RowStatus: PublicEnum.RowStatus.Insert,
                CreatedBy: userID,
                BarcodeMaster: record._id,
                RcvBusinessType: 1,
                BusinessDocID: record.MO,
                LotNumber: record.MOLotNumber,
                ItemMaster: record.ItemMaster,
                RcvUser: userID,
                RcvQty: 1,
                RcvOperation: record.Operation,
                BizRecord: record.BizRecord,
                ConnectArea: record.Operation ? record.Operation.ConnectArea : ''
            });
        });
        var entity = entityCollection.getEntity("RcvRecord");
        entity.save(rcvRecords, function(err, records) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '新增错误';
                newErr.message = '新增入库记录错误，请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, records);
            }
        });
    });
};
